import os
import sys
import typing

from pydantic_settings import BaseSettings


def get_settings():
    """根据环境变量动态创建Settings实例"""
    env = os.getenv("ENV", "dev")
    env_file = f"env/.env.{env}"
    if not os.path.exists(env_file):
        env_file = ".env"  # 回退到根目录的.env文件
    
    class DynamicSettings(BaseSettings):
        model_config = {"env_file": env_file, "env_file_encoding": "utf-8"}
        
        VERSION: str = "0.1.0"
        APP_TITLE: str = "Vue FastAPI Admin"
        PROJECT_NAME: str = "Vue FastAPI Admin"
        APP_DESCRIPTION: str = "Description"

        CORS_ORIGINS: typing.List = ["*"]
        CORS_ALLOW_CREDENTIALS: bool = True
        CORS_ALLOW_METHODS: typing.List = ["*"]
        CORS_ALLOW_HEADERS: typing.List = ["*"]

        DEBUG: bool = True

        PROJECT_ROOT: str = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
        BASE_DIR: str = os.path.abspath(os.path.join(PROJECT_ROOT, os.pardir))
        LOGS_ROOT: str = os.path.join(BASE_DIR, "app/logs")
        SECRET_KEY: str = "3488a63e1765035d386f05409663f55c83bfae3b3c61a932744b20ad14244dcf"  # openssl rand -hex 32
        JWT_ALGORITHM: str = "HS256"
        JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 7  # 7 day
        
        # 数据库配置
        DB_TYPE: str = "sqlite"  # sqlite, mysql, postgres
        MYSQL_HOST: str = "localhost"
        MYSQL_PORT: int = 3306
        MYSQL_USER: str = "root"
        MYSQL_PASSWORD: str = "yourpassword"
        MYSQL_DATABASE: str = "vue_fastapi_admin"
        
        POSTGRES_HOST: str = "localhost"
        POSTGRES_PORT: int = 5432
        POSTGRES_USER: str = "postgres"
        POSTGRES_PASSWORD: str = "yourpassword"
        POSTGRES_DATABASE: str = "vue_fastapi_admin"
        
        SQLITE_PATH: str = "db.sqlite3"
        
        # 时区配置
        TIMEZONE: str = "Asia/Shanghai"
        USE_TZ: bool = False
        
        @property
        def TORTOISE_ORM(self) -> dict:
            """动态生成数据库配置"""
            connections = {}
            
            # 根据当前数据库类型只添加需要的连接
            if self.DB_TYPE == "sqlite":
                connections["sqlite"] = {
                    "engine": "tortoise.backends.sqlite",
                    "credentials": {"file_path": f"{self.BASE_DIR}/{self.SQLITE_PATH}"},
                }
            elif self.DB_TYPE == "mysql":
                connections["mysql"] = {
                    "engine": "tortoise.backends.mysql",
                    "credentials": {
                        "host": self.MYSQL_HOST,
                        "port": self.MYSQL_PORT,
                        "user": self.MYSQL_USER,
                        "password": self.MYSQL_PASSWORD,
                        "database": self.MYSQL_DATABASE,
                    },
                }
            elif self.DB_TYPE == "postgres":
                connections["postgres"] = {
                    "engine": "tortoise.backends.asyncpg",
                    "credentials": {
                        "host": self.POSTGRES_HOST,
                        "port": self.POSTGRES_PORT,
                        "user": self.POSTGRES_USER,
                        "password": self.POSTGRES_PASSWORD,
                        "database": self.POSTGRES_DATABASE,
                    },
                }
            
            return {
                "connections": connections,
                "apps": {
                    "models": {
                        "models": ["app.models", "aerich.models"],
                        "default_connection": self.DB_TYPE,
                    },
                },
                "use_tz": False,
                "timezone": "Asia/Shanghai",
            }
        DATETIME_FORMAT: str = "%Y-%m-%d %H:%M:%S"
    
    return DynamicSettings()


class Settings(BaseSettings):
    VERSION: str = "0.1.0"
    APP_TITLE: str = "Vue FastAPI Admin"
    PROJECT_NAME: str = "Vue FastAPI Admin"
    APP_DESCRIPTION: str = "Description"

    CORS_ORIGINS: typing.List = ["*"]
    CORS_ALLOW_CREDENTIALS: bool = True
    CORS_ALLOW_METHODS: typing.List = ["*"]
    CORS_ALLOW_HEADERS: typing.List = ["*"]

    DEBUG: bool = True

    PROJECT_ROOT: str = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
    BASE_DIR: str = os.path.abspath(os.path.join(PROJECT_ROOT, os.pardir))
    LOGS_ROOT: str = os.path.join(BASE_DIR, "app/logs")
    SECRET_KEY: str = "3488a63e1765035d386f05409663f55c83bfae3b3c61a932744b20ad14244dcf"  # openssl rand -hex 32
    JWT_ALGORITHM: str = "HS256"
    JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 7  # 7 day
    
    # 数据库配置
    DB_TYPE: str = "sqlite"  # sqlite, mysql, postgres
    MYSQL_HOST: str = "localhost"
    MYSQL_PORT: int = 3306
    MYSQL_USER: str = "root"
    MYSQL_PASSWORD: str = "yourpassword"
    MYSQL_DATABASE: str = "vue_fastapi_admin"
    
    POSTGRES_HOST: str = "localhost"
    POSTGRES_PORT: int = 5432
    POSTGRES_USER: str = "postgres"
    POSTGRES_PASSWORD: str = "yourpassword"
    POSTGRES_DATABASE: str = "vue_fastapi_admin"
    
    SQLITE_PATH: str = "db.sqlite3"
    
    # 时区配置
    TIMEZONE: str = "Asia/Shanghai"
    USE_TZ: bool = False
    
    @property
    def TORTOISE_ORM(self) -> dict:
        """动态生成数据库配置"""
        connections = {}
        
        # SQLite 配置
        connections["sqlite"] = {
            "engine": "tortoise.backends.sqlite",
            "credentials": {"file_path": f"{self.BASE_DIR}/{self.SQLITE_PATH}"},
        }
        
        # MySQL 配置
        connections["mysql"] = {
            "engine": "tortoise.backends.mysql",
            "credentials": {
                "host": self.MYSQL_HOST,
                "port": self.MYSQL_PORT,
                "user": self.MYSQL_USER,
                "password": self.MYSQL_PASSWORD,
                "database": self.MYSQL_DATABASE,
            },
        }
        
        # PostgreSQL 配置
        connections["postgres"] = {
            "engine": "tortoise.backends.asyncpg",
            "credentials": {
                "host": self.POSTGRES_HOST,
                "port": self.POSTGRES_PORT,
                "user": self.POSTGRES_USER,
                "password": self.POSTGRES_PASSWORD,
                "database": self.POSTGRES_DATABASE,
            },
        }
        
        return {
            "connections": connections,
            "apps": {
                "models": {
                    "models": ["app.models", "aerich.models"],
                    "default_connection": self.DB_TYPE,
                },
            },
            "use_tz": False,
            "timezone": "Asia/Shanghai",
        }
    DATETIME_FORMAT: str = "%Y-%m-%d %H:%M:%S"


settings = get_settings()
